相关疑难解决方法(0)

从函数返回unique_ptr时的unique_ptr所有权错误

我是unique_ptr的新手.一切都很顺利,直到我遇到一个函数返回一个新的unique_ptr.编译器似乎抱怨可能拥有unique_ptr的多个对象.我不确定如何满足编译器的投诉.任何帮助表示赞赏.

void Bar::Boo()
{
    ...
    // m_Goals is of type std::unique_ptr<Goals>
    auto x = m_Goals->Foo(); // error: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
    //auto x = std::move( m_Goals->Foo() ); // same error
    ...
}


const std::unique_ptr<Goals> Goals::Foo()
{
    std::unique_ptr<Goals> newGoals( new Goals() );
    ...
    return newGoals;
    // also tried "return std::move( newGoals )" based on http://stackoverflow.com/questions/4316727/returning-unique-ptr-from-functions
} // this function compiles
Run Code Online (Sandbox Code Playgroud)

c++ unique-ptr

3
推荐指数
1
解决办法
2872
查看次数

当返回类型为const时,为什么可以修改返回值?

我的印象是,通过声明返回类型const,您可以防止修改数据结构.但是,我测试了这个,我可以修改数据结构.这是为什么?

例如,以下代码1 2 3 4 5 6在编译时打印--std=c++11:

#include <iostream>
#include <set>

using namespace std;
const set<int> f(void) {
    set<int> s = {1, 2, 3, 4, 5};
    return s;
}
int main(void) {
    set<int> s = f();
    s.insert(6);

    for (auto elem: s) {
        cout << elem << " ";
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ const return-type return-value

2
推荐指数
1
解决办法
94
查看次数

为什么c++中的const转换运算符没有意义?

在《C++ Primer》练习14.47中,有一个问题:

解释一下这两个转换运算符的区别:

struct Integral {
    operator const int();
    operator int() const;
}
Run Code Online (Sandbox Code Playgroud)

我不知道为什么我在 GitHub 上找到的答案说第一个const没有意义,因为对于一个转换运算符不应该定义返回类型,这里const未指定,它将被编译器忽略。但我也发现有些人说这意味着函数将返回一个const值。

所以,我想知道哪一个是正确的,为什么?

c++ overloading constants

2
推荐指数
1
解决办法
282
查看次数

非成员函数是否可以返回const值?

如果是这样,怎么样?这个问题甚至有意义吗?

在我的情况下,调用者修改返回的对象是没有意义的,所以我想将其标记为不可修改.

c++ const

0
推荐指数
1
解决办法
1198
查看次数

const之前的const和c ++之后的const

在函数标题/ prototype之后const之前和const之间有什么区别?另外在下面的例子中做什么?

例如.

const E& top() const throw(StackEmpty);
Run Code Online (Sandbox Code Playgroud)

c++

-4
推荐指数
1
解决办法
84
查看次数