我试图创建和使用make_unique的std::unique_ptr,以同样的方式std::make_shared对存在std::shared_ptr 这里描述.Herb Sutter 提到了可能的实现make_unique,如下所示:
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}
Run Code Online (Sandbox Code Playgroud)
它似乎对我不起作用.我正在使用以下示例程序:
// testproject.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <memory>
#include <utility>
struct A {
A(int&& n) { std::cout << "rvalue overload, n=" << n << "\n"; }
A(int& n) { std::cout << "lvalue overload, n=" << n << …Run Code Online (Sandbox Code Playgroud) 我想创建一个if声明,分配和检查变量的位置.如果变量的值是可接受的,我想在if体内使用它.这是我认为我能做到的一个例子:
if ((int result = Foo()) != 0) {
// use result
}
Run Code Online (Sandbox Code Playgroud)
我假设Foo()返回一些值,它被赋值给result赋值运算符=,并由赋值运算符返回,最后检0入!= 0.不幸的是,它导致编译错误:
main.cpp:31:10: error: expected primary-expression before ‘int’
if ((int i = Foo()) != 0)
^
main.cpp:31:10: error: expected ‘)’ before ‘int’
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种错误?有什么方法可以解决它?
请考虑以下代码:
#include <iostream>
int main(int argc, char ** argv) {
std::set<int*> ints;
for (int i = 0; i < 10; i ++) {
int * k = new int(i);
ints.insert(k);
}
for (auto i : ints) {
// some order-sensitive operations, for example:
std::cout << (*i) << " ";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
其中第二个循环对从集合中取出元素的顺序敏感.在程序的不同运行中,这种程序的执行结果是否可能会有所不同?
据我所知,在std::set内部对元素进行排序.由于内存中的分配不一定具有增加的地址,因此可能(尽管不太可能)该程序的输出不会0 1 2 3 4 5 6 7 8 9?