C++14 question/validation

Status
Not open for further replies.

drogin

Ars Tribunus Angusticlavius
8,284
Subscriptor++
So, I started my career with C++98, but a lot has changed since then and I've gone back to get myself reaquainted with my old friend. Turns out that my old friend has changed a lot!

At this point I've read through the most recent editions of:

The C++ Programming Language
Effective C++
Modern Effective C++

So, let me lay out what I did, then take a look at the code. I'm happy to hear that I'm being stupid, and would even accept style/convention notes since I haven't had the time to read through any style guides.

What I am looking to do is create a class that contains a static factory method. The factory method will perfect forward to a private constructor. This is to, I believe, force users of my type to always have it wrapped in a std::unique_ptr.

Further I'm pretending that I want to isolate implementation details from my type's users, so I'm applying the PIMPL idiom.

This is obviously a contrived example.

Code:
// Foo.h

#include <memory>

namespace F {
    class Foo {

        public:
            ~Foo();

            template<typename... Ts>
            static std::unique_ptr<Foo> create(Ts&&... params) {
                return std::unique_ptr<Foo>(new Foo(
                    std::forward<decltype(params)>(params)...
                ));
            }
            
            int x();

        private:
            struct Impl;
            std::unique_ptr<Impl> pImpl;

            Foo(int x);
    };
}

Code:
// Foo.cpp

#include <Foo.h>

using namespace F;

struct Foo::Impl {
    int x;
};

// public
Foo::~Foo() = default;

int Foo::x() {
    return pImpl->x;
}

// private
Foo::Foo(int x) : pImpl{std::make_unique<Impl>()} {
    pImpl->x = x;
}

Code:
// main.cpp

#include <iostream>
#include <memory>

#include "Foo.h"

int main() {
    auto f = F::Foo::create(3);

    std::cout << "x is: " << f->x() << std::endl;

    return 0;
}

This compiles and works fine with the following compiler:

Code:
$ clang++ --version
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.4.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

Here are my questions/points of validation:

  • Do I really need to wrap my pImpl member in a std::unique_ptr? If this were a raw pointer, I suppose I'd have to just provide a deconstructor that deletes it...but that would be it right? I just want to make sure I'm not trading efficiency for not having to write code.
  • In Modern Effective C++, it is stated to prefer std::make_unique over the 'new' operator. This makes sense, but in my case I can't use std::make_unique in the Foo::create function because it is trying to forward to a private constructor. I tried, it didn't compile (which makes sense to me). Is this an acceptable place to use new and violate the prefer?
  • Based on what I read in Modern Effective C++, it seems to me that the Foo::create function is essentially a specialization of the std::make_unique function. If so, would it make more sense to just specialize std::make_unique? I didn't try this...I'm just speculating. I mean, if my constructor were public then I'd just use std::make_unique. However, that's counter to my concern: I want to force all users of the Foo type to use a std::unique_ptr. The only way I can really do that by making the Foo::create function the only way to construct a Foo. Right? Crazy pants?
 

RAOF

Ars Tribunus Militum
2,733
Looks about right, modulo being clearly overkill for this trivial example :).

A top-level design question: why is it important that Foo only ever be allocated on the heap (which is what only providing a std::unique_ptr factory does)? That's odd to me, and I can't think off the top of my head why you'd want to do that.
  • Do I really need to wrap my pImpl member in a std::unique_ptr? If this were a raw pointer, I suppose I'd have to just provide a deconstructor that deletes it...but that would be it right? I just want to make sure I'm not trading efficiency for not having to write code.
A unique_ptr is exactly a raw pointer plus a (determined-at-compile-time) destructor that deletes it; you're not trading efficiency here. It's exactly the same size as a raw pointer, and accessing it requires exactly the same number of dereferences.

  • Based on what I read in Modern Effective C++, it seems to me that the Foo::create function is essentially a specialization of the std::make_unique function. If so, would it make more sense to just specialize std::make_unique? I didn't try this...I'm just speculating. I mean, if my constructor were public then I'd just use std::make_unique. However, that's counter to my concern: I want to force all users of the Foo type to use a std::unique_ptr. The only way I can really do that by making the Foo::create function the only way to construct a Foo. Right? Crazy pants?

Hm. Not compile-tested, but
Code:
class Foo {
    template<typename... Ts>
    friend std::make_unique<Foo>(Ts&&... args);
}
Should allow you to write a specialisation of std::make_unique<Foo> that accesses private constructors. I'm not sure whether you should do this, because I don't understand why you want the only-allocatable-on-the-heap requirement.
 

MilleniX

Ars Tribunus Angusticlavius
8,141
Subscriptor++
[url=http:/civis/viewtopic.php?p=31445139#p31445139:2kgluyrn said:
RAOF[/url]":2kgluyrn]
  • Based on what I read in Modern Effective C++, it seems to me that the Foo::create function is essentially a specialization of the std::make_unique function. If so, would it make more sense to just specialize std::make_unique? I didn't try this...I'm just speculating. I mean, if my constructor were public then I'd just use std::make_unique. However, that's counter to my concern: I want to force all users of the Foo type to use a std::unique_ptr. The only way I can really do that by making the Foo::create function the only way to construct a Foo. Right? Crazy pants?

Hm. Not compile-tested, but
Code:
class Foo {
    template<typename... Ts>
    friend std::make_unique<Foo>(Ts&&... args);
}
Should allow you to write a specialisation of std::make_unique<Foo> that accesses private constructors. I'm not sure whether you should do this, because I don't understand why you want the only-allocatable-on-the-heap requirement.
This makes assumptions about the library's implementation of make_unique, that it doesn't have any sort of helper functions inside it that would actually have to be declared as friends to make this work. An implementation that did that would be kinda wacky, but it's not something that would be forbidden.
 

drogin

Ars Tribunus Angusticlavius
8,284
Subscriptor++
[url=http:/civis/viewtopic.php?p=31447833#p31447833:31zs2vyv said:
MilleniX[/url]":31zs2vyv]
[url=http:/civis/viewtopic.php?p=31445139#p31445139:31zs2vyv said:
RAOF[/url]":31zs2vyv]
  • Based on what I read in Modern Effective C++, it seems to me that the Foo::create function is essentially a specialization of the std::make_unique function. If so, would it make more sense to just specialize std::make_unique? I didn't try this...I'm just speculating. I mean, if my constructor were public then I'd just use std::make_unique. However, that's counter to my concern: I want to force all users of the Foo type to use a std::unique_ptr. The only way I can really do that by making the Foo::create function the only way to construct a Foo. Right? Crazy pants?

Hm. Not compile-tested, but
Code:
class Foo {
    template<typename... Ts>
    friend std::make_unique<Foo>(Ts&&... args);
}
Should allow you to write a specialisation of std::make_unique<Foo> that accesses private constructors. I'm not sure whether you should do this, because I don't understand why you want the only-allocatable-on-the-heap requirement.
This makes assumptions about the library's implementation of make_unique, that it doesn't have any sort of helper functions inside it that would actually have to be declared as friends to make this work. An implementation that did that would be kinda wacky, but it's not something that would be forbidden.

Yes, I thought about friendship, but my understanding is that is very much to be avoided unless you own all sides of the parties involved.
 

drogin

Ars Tribunus Angusticlavius
8,284
Subscriptor++
[url=http:/civis/viewtopic.php?p=31445139#p31445139:qteoqvvn said:
RAOF[/url]":qteoqvvn]Looks about right, modulo being clearly overkill for this trivial example :).

A top-level design question: why is it important that Foo only ever be allocated on the heap (which is what only providing a std::unique_ptr factory does)? That's odd to me, and I can't think off the top of my head why you'd want to do that.
  • Do I really need to wrap my pImpl member in a std::unique_ptr? If this were a raw pointer, I suppose I'd have to just provide a deconstructor that deletes it...but that would be it right? I just want to make sure I'm not trading efficiency for not having to write code.
A unique_ptr is exactly a raw pointer plus a (determined-at-compile-time) destructor that deletes it; you're not trading efficiency here. It's exactly the same size as a raw pointer, and accessing it requires exactly the same number of dereferences.

  • Based on what I read in Modern Effective C++, it seems to me that the Foo::create function is essentially a specialization of the std::make_unique function. If so, would it make more sense to just specialize std::make_unique? I didn't try this...I'm just speculating. I mean, if my constructor were public then I'd just use std::make_unique. However, that's counter to my concern: I want to force all users of the Foo type to use a std::unique_ptr. The only way I can really do that by making the Foo::create function the only way to construct a Foo. Right? Crazy pants?

Hm. Not compile-tested, but
Code:
class Foo {
    template<typename... Ts>
    friend std::make_unique<Foo>(Ts&&... args);
}
Should allow you to write a specialisation of std::make_unique<Foo> that accesses private constructors. I'm not sure whether you should do this, because I don't understand why you want the only-allocatable-on-the-heap requirement.

As to why I want the only-allocatable-on-the-heap requirement.

I frankly didn't think about it in those terms.

I'm building this class to manage a resource from a third-party library which itself uses a factory function that only returns a pointer. Further, the 3rd-party lib uses a special deallocation function.

My thought process at this point was to wrap the 3rd-party pointer in a resource management class that is guaranteed to be cleaned up when it goes out of scope. In this case, I'm doing that with something that looks like Foo.

This could be where my logic starts to go off.

If I wanted to be able to create Foo in automatic memory, then I'd have to have a constructor still right? That way I could do something like:

Code:
int main() {

    // ...

    Foo bar{p};

    // ...
}

Where in the above 'p' is a pointer to this 3rd-party resource. This would mean that the calling scope that initialized 'bar' would need to be able to generate the resource, i.e. include the headers and call the allocator for 'p'.

Also, it would mean I'd be able to 'new' up a Foo and circumvent using something like std::unique_ptr.
 

RAOF

Ars Tribunus Militum
2,733
[url=http:/civis/viewtopic.php?p=31445139#p31445139:2pozv9fo said:
RAOF[/url]":2pozv9fo]
  • Based on what I read in Modern Effective C++, it seems to me that the Foo::create function is essentially a specialization of the std::make_unique function. If so, would it make more sense to just specialize std::make_unique? I didn't try this...I'm just speculating. I mean, if my constructor were public then I'd just use std::make_unique. However, that's counter to my concern: I want to force all users of the Foo type to use a std::unique_ptr. The only way I can really do that by making the Foo::create function the only way to construct a Foo. Right? Crazy pants?

Hm. Not compile-tested, but
Code:
class Foo {
    template<typename... Ts>
    friend std::make_unique<Foo>(Ts&&... args);
}
Should allow you to write a specialisation of std::make_unique<Foo> that accesses private constructors. I'm not sure whether you should do this, because I don't understand why you want the only-allocatable-on-the-heap requirement.
This makes assumptions about the library's implementation of make_unique, that it doesn't have any sort of helper functions inside it that would actually have to be declared as friends to make this work. An implementation that did that would be kinda wacky, but it's not something that would be forbidden.
Oh, no. I meant that with this you'd provide your own std::make_unique<Foo> specialisation (which you should be able to do), not relying on friend to make the standard library's implementation work. That would indeed be brittle.

…
As to why I want the only-allocatable-on-the-heap requirement.

I frankly didn't think about it in those terms.

I'm building this class to manage a resource from a third-party library which itself uses a factory function that only returns a pointer. Further, the 3rd-party lib uses a special deallocation function.

My thought process at this point was to wrap the 3rd-party pointer in a resource management class that is guaranteed to be cleaned up when it goes out of scope. In this case, I'm doing that with something that looks like Foo.
So you're re-implementing std::unique_ptr? Note: you can have the type std::unique_ptr<ThirdPartyType, &third_party_deallocate_function> which will wrap a ThirdPartyType* and deallocate it with the specified deallocation function (you may need to wrap that to provide the appropriate signature, but it should be trivial).

This could be where my logic starts to go off.

If I wanted to be able to create Foo in automatic memory, then I'd have to have a constructor still right? That way I could do something like:

Code:
int main() {

    // ...

    Foo bar{p};

    // ...
}

Where in the above 'p' is a pointer to this 3rd-party resource. This would mean that the calling scope that initialized 'bar' would need to be able to generate the resource, i.e. include the headers and call the allocator for 'p'.
Why are you passing in p to the Foo constructor? An idiomatic resource wrapper type would construct a 3rd-party pointer in its constructor, optionally store it internally in a unique_ptr, and delete it in the destructor. The ability for unique_ptr to store null is an antifeature compromise required by decades of existing code. If you can avoid having invalid instances of Foo it will make your code simpler.

Also, it would mean I'd be able to 'new' up a Foo and circumvent using something like std::unique_ptr.
This is not something C++ can enforce for you; “auto raw_ptr = std::make_unique<Foo>().release()” gets you an unmanaged pointer out of your only-supply-a-unique-pointer interface.
 
Your use of std::forward isn't quite idiomatic. Instead of using decltype you should use the template parameter.

Code:
            template<typename... Ts>
            static std::unique_ptr<Foo> create(Ts&&... params) {
                return std::unique_ptr<Foo>(new Foo(std::forward<Ts>(params)...));
            }

Using decltype does happen to work, but it's more complicated and you should forget it in favor of just using the idiom.

[url=http:/civis/viewtopic.php?p=31435267#p31435267:2adtrorv said:
drogin[/url]":2adtrorv]

  • Do I really need to wrap my pImpl member in a std::unique_ptr? If this were a raw pointer, I suppose I'd have to just provide a deconstructor that deletes it...but that would be it right? I just want to make sure I'm not trading efficiency for not having to write code.
You'd want to remember the 'rule of five'. If you write your own destructor but not a copy constructor or copy assignment operator then you get default copying and assignment, which would lead to double frees of the raw pointer member. Using std::unique_ptr lets you use the 'rule of zero', and there's no performance penalty vs. writing the usual special member functions for a raw pointer.

  • In Modern Effective C++, it is stated to prefer std::make_unique over the 'new' operator. This makes sense, but in my case I can't use std::make_unique in the Foo::create function because it is trying to forward to a private constructor. I tried, it didn't compile (which makes sense to me). Is this an acceptable place to use new and violate the prefer?
Yeah, I think so. There are some more complicated solutions, but I'm not sure they're worth it.

  • Based on what I read in Modern Effective C++, it seems to me that the Foo::create function is essentially a specialization of the std::make_unique function. If so, would it make more sense to just specialize std::make_unique? I didn't try this...I'm just speculating. I mean, if my constructor were public then I'd just use std::make_unique. However, that's counter to my concern: I want to force all users of the Foo type to use a std::unique_ptr. The only way I can really do that by making the Foo::create function the only way to construct a Foo. Right? Crazy pants?
No. make_unique is not intended to be an extension point like that. And if you mean literally a template specialization in the std namespace, you can't do that anyway. (You can't do partial specializations of functions, so you'd have to write an overload instead of a template specialization, and it's illegal to add such declarations to the std namespace.)

However if you just want to use 'make_unique' as a convention for naming your static creation methods, there's nothing technically wrong with that.

If I wanted to be able to create Foo in automatic memory, then I'd have to have a constructor still right? [...] Where in the above 'p' is a pointer to this 3rd-party resource. This would mean that the calling scope that initialized 'bar' would need to be able to generate the resource, i.e. include the headers and call the allocator for 'p'.

No, you could still hide the third party library. Your class would internally create the third party type, and the interface wouldn't need to expose anything about the third party type. Here's an example.
 

drogin

Ars Tribunus Angusticlavius
8,284
Subscriptor++
RAOF":2srbaxo4 said:
…
As to why I want the only-allocatable-on-the-heap requirement.

I frankly didn't think about it in those terms.

I'm building this class to manage a resource from a third-party library which itself uses a factory function that only returns a pointer. Further, the 3rd-party lib uses a special deallocation function.

My thought process at this point was to wrap the 3rd-party pointer in a resource management class that is guaranteed to be cleaned up when it goes out of scope. In this case, I'm doing that with something that looks like Foo.
So you're re-implementing std::unique_ptr? Note: you can have the type std::unique_ptr<ThirdPartyType, &third_party_deallocate_function> which will wrap a ThirdPartyType* and deallocate it with the specified deallocation function (you may need to wrap that to provide the appropriate signature, but it should be trivial).

I could be, but I don't think that's what I'm doing. What I'm trying to do is enforce the usage of std::unique_ptr to the extent possible. If I just created a wrapper class for the underlying resource, I would be hoping that client code would use std::unique_ptr. In my case, I want to force them to. Again, this may be crazy. Maybe it isn't the way it is done, but it does seem to be something Myers hints at.

RAOF":2srbaxo4 said:
This could be where my logic starts to go off.

If I wanted to be able to create Foo in automatic memory, then I'd have to have a constructor still right? That way I could do something like:

Code:
int main() {

    // ...

    Foo bar{p};

    // ...
}

Where in the above 'p' is a pointer to this 3rd-party resource. This would mean that the calling scope that initialized 'bar' would need to be able to generate the resource, i.e. include the headers and call the allocator for 'p'.
Why are you passing in p to the Foo constructor? An idiomatic resource wrapper type would construct a 3rd-party pointer in its constructor, optionally store it internally in a unique_ptr, and delete it in the destructor. The ability for unique_ptr to store null is an antifeature compromise required by decades of existing code. If you can avoid having invalid instances of Foo it will make your code simpler.

You're totally right. I didn't take enough time to check my own post. I wouldn't have the client passing in a pointer to the underlying resource type. I'd have the client pass in the parameters necessary to properly construct one. I guess my point is just that I would need a constructor in order to allow that, and thus clients could trivially created unmanaged objects on the heap.

RAOF":2srbaxo4 said:
Also, it would mean I'd be able to 'new' up a Foo and circumvent using something like std::unique_ptr.
This is not something C++ can enforce for you; “auto raw_ptr = std::make_unique<Foo>().release()” gets you an unmanaged pointer out of your only-supply-a-unique-pointer interface.

Again, you're totally right, they could do that. I just think that is a much bigger hurdle for them to jump over, whereas using 'new' is pretty common and so it wouldn't even take a second thought.
 

drogin

Ars Tribunus Angusticlavius
8,284
Subscriptor++
[url=http:/civis/viewtopic.php?p=31457455#p31457455:3pxidlwc said:
bames53[/url]":3pxidlwc]Your use of std::forward isn't quite idiomatic. Instead of using decltype you should use the template parameter.

Code:
            template<typename... Ts>
            static std::unique_ptr<Foo> create(Ts&&... params) {
                return std::unique_ptr<Foo>(new Foo(std::forward<Ts>(params)...));
            }

Using decltype does happen to work, but it's more complicated and you should forget it in favor of just using the idiom.

Hmm. You're right, and I did have that at one point. However, I was copying from Myers...so I just deferred to that. Is there some case the decltype covers and using 'Ts' doesn't?

[url=http:/civis/viewtopic.php?p=31457455#p31457455:3pxidlwc said:
bames53[/url]":3pxidlwc]
[url=http:/civis/viewtopic.php?p=31435267#p31435267:3pxidlwc said:
drogin[/url]":3pxidlwc]
If I wanted to be able to create Foo in automatic memory, then I'd have to have a constructor still right? [...] Where in the above 'p' is a pointer to this 3rd-party resource. This would mean that the calling scope that initialized 'bar' would need to be able to generate the resource, i.e. include the headers and call the allocator for 'p'.

No, you could still hide the third party library. Your class would internally create the third party type, and the interface wouldn't need to expose anything about the third party type. Here's an example.

Thanks for the link, and you're right as was RAOF. I definitely misspoke. I'd simply need to expose the private constructor as public so that I could use those parameters to create the underlying resource.
 

drogin

Ars Tribunus Angusticlavius
8,284
Subscriptor++
[url=http:/civis/viewtopic.php?p=31467851#p31467851:268g536w said:
bames53[/url]":268g536w]
Is there some case the decltype covers and using 'Ts' doesn't?

In a generic lambda expression where the template parameter isn't named you would have to use decltype instead. However I'm not sure there's much need for perfect forwarding in lambda expressions. Where did you see Meyers using decltype in std::forward?

Evidently in my imagination.

I conflated two examples from two separate Items in Modern Effective C++, then mixed in a little code I saw on StackOverflow. My bad.
 
Status
Not open for further replies.