0

我有一个接受双指针的 Point 构造函数。我这样做如下

Point::Point(double* p)
   : mX(p[0]), mY(p[1]), mZ(p[2])
{}

Point pt( []() -> double* {double p[3] = {1, 2, 3}; return p;}() );

有没有更简单的方法来在一行中构造一个具有指定值的指针?

4

3 回答 3

4

The simplest way to do this would be to declare a local array and pass a pointer to that:

double p[3] = {1, 2, 3};
Point pt(p);

Alternatively, consider writing a new constructor that lets you pass the three coordinates directly:

Point::Point(double x, double y, double z)
    : mX(x), mY(y), mZ(z)
{ }

If adding a constructor is not possible then you could use a factory:

Point make_point(double x, double y, double z)
{
    double p[3] = { x, y, z };

    return Point(p);
}
于 2013-10-06T03:26:02.010 回答
3

[EDIT] This creates the temporary array on the stack, so it will be a lot faster that the other two options, which involve a memory allocation (new / delete):

Point pt( &(double[3]){1, 2, 3}[0] );

To avoid a memory leak and actually return a pointer, you have to make it somewhat longer:

Point pt( std::unique_ptr<double>(
    []() -> double* { return new double[3]{1, 2, 3}; }()
    ).get() );

Another option:

Point pt( std::vector<double>{1,2,3}.data() );
于 2013-10-06T03:28:49.260 回答
2

Your code does not work: the array returned from the lambda function is destroyed after returning from the lambda but before passing it on to the constructor where you want to see it. The code probably appears to work but that is just the worst case of undefined behavior.

Personally, I think you should consider a better interface. If you can't change your interface, you might want to use something like this:

typedef double array[3];
Point pt(&(array{ 1.2, 2.3, 3.4 })[0]);
于 2013-10-06T03:33:52.153 回答